package org.example.jdbc;

import java.sql.*;
import java.util.Scanner;

/**
 * 实现注册功能
 * 返回响应：
 * 1 注册成功
 * 2 用户名被占用，请换一个
 */
public class JDBCReg {
    public static void main(String[] args) {
        try ( Connection connection= DBUtil.getConnection();){
            Scanner scanner= new Scanner(System.in);
            System.out.println("请输入用户名");
            String username = scanner.nextLine();
            System.out.println("请输入密码：");
            String password = scanner.nextLine();
            System.out.println("请输入昵称：");
            String nickname = scanner.nextLine();
            System.out.println("请输入年龄：");
            int age = scanner.nextInt();
//            确认用户名是否被占用
            String sql1 = "SELECT id FROM user WHERE username=?";
            PreparedStatement prt1 = connection.prepareStatement(sql1);
            prt1.setString(1,username);
            ResultSet rs = prt1.executeQuery();
            if (rs.next()){//被占用
                System.out.println("用户名太受欢迎了，请换一个！");
            }else {//未被占用
                String sql2 = "INSERT INTO user (username,password,nickname,age) VALUES (?,?,?,?)";
                PreparedStatement prt2 = connection.prepareStatement(sql2);
                prt2.setString(1,username);
                prt2.setString(2,password);
                prt2.setString(3,nickname);
                prt2.setInt(4,age);
                prt2.executeUpdate();
                System.out.println("注册成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
